import traceback
import sys

def getTraceStackMsg():
    tb = sys.exc_info()[2]
    msg = ''
    for i in traceback.format_tb(tb):
        msg += i
    return msg

class Singleton(object):  
    def __new__(cls, *args, **kw):  
        if not hasattr(cls, '_instance'):  
            orig = super(Singleton, cls)  
            try:
                 cls._instance = orig.__new__(cls, *args, **kw)  
            except Exception,e:
                 pass
            try:
                 cls._instance = orig.__new__(cls)  
            except Exception,e:
                 pass
            method_name = "__single_init__"
            try:
                method = getattr(cls._instance, method_name)
            except Exception,e:
                print "metho %s not found" % method_name
            try:
                method(*args, **kw)
            except Exception,e:
                try:
                    method()
                except Exception,e:
                    print "method %s call fail" % method_name
                    print str(e) + getTraceStackMsg()
        return cls._instance
try:
    import gevent
    import gevent.monkey
    gevent.monkey.patch_socket()
    from gevent.queue import Queue
except Exception,e:
    print "not install gevent"
        
try:
    import pymysql
    class MysqlPool(Singleton):
        def __single_init__(self,pool_size=10,host='localhost',port=3306,user='root',passwd='123',db='ere',charset='utf8'):
            self.con_que=Queue()
            self.cur_que=Queue()
            try:
                for i in range(pool_size):
                    conn=pymysql.connect(host=host,port=port,user=user,passwd=passwd,db=db,charset=charset)
                    self.con_que.put(conn)
                    cursor = conn.cursor(pymysql.cursors.DictCursor)
                    cursor.execute("set names '%s'" % charset)
                    self.cur_que.put(conn.cursor(pymysql.cursors.DictCursor))
                print "inti mysql pool suc"
            except Exception,e:
                print str(e) + getTraceStackMsg()
    
        def empty(self):
            return self.cur_que.empty()
    
        def get(self):
            return self.cur_que.get()
    
        def put(self, obj):
            self.cur_que.put(obj)
except Exception,e:
    print "not install pymysql"

